#include"Mutex.hpp"
#include<string>
#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<stdio.h>

using namespace MutexModule;

int ticket = 1000;

class ThreadData
{
public:
    ThreadData(const std::string &n, Mutex &lock)
        :name(n),
        lockp(&lock)
    {}
    ~ThreadData()
    {}
    std::string name;//name 是一个字符串，用于标识线程的名称
    Mutex *lockp;//lockp 是一个指向 Mutex 对象的指针，用于线程同步

};

void *route(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while(1)
    {
        LockGuard guard(td->lockp);//// 加锁完成, RAII风格的互斥锁的实现
        if (ticket > 0)
        {
            usleep(10000);
            std::cout << td->name << " sells ticket:" << ticket-- << std::endl;
            ticket--;
        }
        else
        {
            break;
        }

        usleep(1230);
    }

    return nullptr;

}

int main()
{
    Mutex lock;
    pthread_t t1, t2, t3, t4;
    ThreadData *td1 = new ThreadData("thread 1", lock);
    pthread_create(&t1, NULL, route, td1);

    ThreadData *td2 = new ThreadData("thread 2", lock);
    pthread_create(&t2, NULL, route, td2);

    ThreadData *td3 = new ThreadData("thread 3", lock);
    pthread_create(&t3, NULL, route, td3);

    ThreadData *td4 = new ThreadData("thread 4", lock);
    pthread_create(&t4, NULL, route, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    return 0;
}